﻿using System;
using System.Collections.Generic;
using System.Text;
using XMK.Utils;
using XMK.Framework.Model;
using System.Web;
using System.Web.SessionState;

namespace XMK.Framework.Web
{
    /// <summary>
    /// 安全认证HttpHandler的父类
    /// </summary>
    /// <typeparam name="T">数据返回类型</typeparam>
    public abstract class BaseHandler<T> : SecureHttpHandlerBase, IRequiresSessionState
    {
        #region 属性
        /// <summary>
        /// 接受前台data内的字符串
        /// </summary>
        public string JsonString { get; set; }
        /// <summary>
        /// JsonString序列化后的对象
        /// </summary>
        public RequestInfo RequestInfo { get; set; }
        #endregion
        /// <summary>
        /// 接收到请求后的参数处理类
        /// </summary>
        public override void Process()
        {
            LogHelper.WriteLog(LogType.Debug, "Handle请求处理开始：" + this.Context.Request.Url.ToString());
            this.JsonString = this.Context.Request["data"];
            ResponseInfo<T> responseInfo = new ResponseInfo<T>();
            string strReturn = string.Empty;
            try
            {
                if (!string.IsNullOrEmpty(this.JsonString))
                {
                    this.RequestInfo = JsonHelper.FromJsonMs<RequestInfo>(this.JsonString);
                }
                else
                {
                    this.RequestInfo = new RequestInfo();
                    // 接收url中的参数
                    this.RequestInfo.Page.PageSize = ParseHelper.Parse<int>(this.GetRequest("PageSize"), 20);
                    this.RequestInfo.Page.CurrentPage = ParseHelper.Parse<int>(this.GetRequest("CurrentPage"), 1);

                    this.RequestInfo.ReturnType = this.GetRequest("ReturnType");
                    this.RequestInfo.TerminalType = this.GetRequest("UserType");
                    this.RequestInfo.OsType = ParseHelper.Parse<string>(this.GetRequest("OsType"), "0");
                }
                //默认为Json格式传递信息
                if (string.IsNullOrEmpty(this.RequestInfo.ReturnType))
                    this.RequestInfo.ReturnType = "json";
                // 登录用户
                this.RequestInfo.UserID = this.UserID;

                responseInfo.State = 0;
                responseInfo.Page = this.RequestInfo.Page;
                ProcRequest(ref responseInfo);
            }
            catch (Exception ex)
            {
                responseInfo.ErrMsg = ex.Message;
                responseInfo.State = 1;
                responseInfo.Data = default(T);
                responseInfo.Page = null;
                LogHelper.WriteLog(LogType.Error, "Handle请求处理异常：" + ex.ToString());
            }
            try
            {
                switch (this.RequestInfo.ReturnType)
                {
                    case "json":
                        this.Context.Response.ContentType = "text/plain";
                        strReturn = JsonHelper.ToJson(responseInfo);
                        break;
                    case "jsonp":
                        this.Context.Response.ContentType = "text/plain";
                        strReturn = JsonHelper.ToJson(responseInfo);
                        break;
                    default:
                        this.Context.Response.ContentType = "text/xml";
                        strReturn = XmlHelper.SerializerToString(responseInfo, responseInfo.Data.GetType());
                        break;
                }
            }
            catch (Exception ex)
            {
                responseInfo.ErrMsg = "序列化返回值出错！";
                responseInfo.State = 1;
                responseInfo.Data = default(T);
                responseInfo.Page = null;
                strReturn = JsonHelper.ToJson(responseInfo);
                LogHelper.WriteLog(LogType.Error, "序列化返回值异常：" + ex.ToString());
            }
            finally
            {
                LogHelper.WriteLog(LogType.Debug, "Handle请求处理结束：" + strReturn);
                SetResopnse(strReturn.Trim());
            }

        }
        /// <summary>
        /// 获取请求的参数
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        protected string GetRequest(string para)
        {
            return this.Context.Request.Params[para];
        }
        #region 子类重写方法
        /// <summary>
        /// 子类具体逻辑实现方法
        /// </summary>
        /// <param name="responseInfo">返回至前台结果</param>
        protected abstract void ProcRequest(ref ResponseInfo<T> responseInfo);
        /// <summary>
        /// 对返回结果进行处理
        /// </summary>
        /// <param name="strReturn">返回的字符串</param>
        public virtual void SetResopnse(string strReturn)
        {
            this.Context.Response.Clear();
            this.Context.Response.BufferOutput = true;
            this.Context.Response.Charset = "utf-8";
            this.Context.Response.ContentEncoding = System.Text.Encoding.UTF8; //这个是新加上的
            // 增加jsonp处理方法
            string callback = Context.Request["jsonpcallback"];
            if(string.IsNullOrEmpty(callback)) callback = Context.Request["callback"];

            if (!string.IsNullOrEmpty(callback) || this.RequestInfo.ReturnType == "jsonp" )
            {
                strReturn = callback + "(" + strReturn + ")";
            }
            this.Context.Response.AppendHeader("Content-Length", Encoding.UTF8.GetBytes(strReturn).Length.ToString());
            this.Context.Response.Write(strReturn);
            this.Context.Response.End();
        }
        #endregion
    }
}
